﻿/// <reference path="../../Plugins/jquery-1.10.2.min.js" />
/// <reference path="../../Plugins/jquery.form.min.js" />

$(document).ready(function () {
    $('#navbar-left li').each(function () {
        $(this).removeClass('active');
        if ($(this).find('i').hasClass('fa-users')) {
            $(this).addClass('active');
        }
    })
})

function AdminListUser(total, pageSize, pageIndex, order) {

    //Private fileds
    var _pageSize = pageSize;
    var _pageIndex = pageIndex;
    var _total = total;
    var _order = order;
    var _baseUrl = '/api/ApiLibUser/GetData';

    var _dataService = new DataService();

    //as
    this.Init = function () {
        Paging();
        DelegateEvent();
    };

    //private function
    function Paging() {
        var totalPages = (_total < pageSize) ? 1 : (Math.floor(_total / _pageSize) + 1);
        if (_total > 0) {
            var options = {
                bootstrapMajorVersion: 3,
                currentPage: _pageIndex,
                totalPages: totalPages,
                size: 'normal',
                useBootstrapTooltip: true,
                tooltipTitles: function (type, page, current) {
                    switch (type) {
                        case "first":
                            return "Về trang đầu";
                        case "prev":
                            return "Trang trước";
                        case "next":
                            return "Trang tiếp";
                        case "last":
                            return "Về trang cuối";
                        case "page":
                            return "Trang " + page;
                    }
                },
                onPageClicked: function (e, originalEvent, type, page) {
                    var url = _baseUrl + '?index=' + page + '&size=' + _pageSize + '&order=' + _order;

                    _dataService.Get(url, successCallback);
                }
            };
            $('#paging').bootstrapPaginator(options);
        }
    }

    function successCallback(data, textStatus, jqXHR) {
        InsertDocumentItem(data);
        if (data.total != _total) {
            var newTotal = (data.total < pageSize) ? 1 : Math.floor(data.total / _pageSize);
            var newOptions = {
                totalPages: newTotal
            };
            $('#paging').bootstrapPaginator(newOptions);
        }
    }

    function InsertDocumentItem(data) {
        if (!data) {
            return;
        }
        $('#tableData>tbody').empty();
        for (var i = 0; i < data.data.length; i++) {
            var html = '<tr>' +
                            '<td>' + (i + 1).toString() + '</td>' +
                            '<td>' + ((data.data[i].UserID != null) ? data.data[i].UserID : '') + '</td>' +
                            '<td>' + ((data.data[i].UserName != null) ? data.data[i].UserName : '') + '</td>' +
                            '<td>' +
                                '<button class="btn btn-default btn-xs table-action" value="' + ((data.data[i].UserID != null) ? data.data[i].UserID : '#') + '"><i class="fa fa-info-circle"></i></button>' +
                                //'<button class="btn btn-default btn-xs table-action" value="' + ((data.data[i].UserId != null) ? data.data[i].DocumentId : '#') + '"><i class="fa fa-trash-o"></i></button>' +
                            '</td>' +
                       '</tr>';
            $('#tableData>tbody').append(html);
        }
    }

    function DelegateEvent() {
        //Edit
        $('#tableData>tbody').delegate('td>button', 'click', function (e) {
            e.preventDefault();
            var self = $(this);
            var pos = self.closest('tr').index();
            if (pos != null) {
                if (self.find('i').hasClass('fa-info-circle')) {
                    ResetModal();
                    //Set data to modal
                    _dataService.Get('/api/ApiLibUser/GetById?userId=' + self.attr('value'), function (data, textStatus, jqXHR) {
                        var roleId = data.data.RoleId;
                        $('#muserId').val(data.data.UserID);
                        $('#muserName').val(data.data.UserName);
                        //Add Role
                        _dataService.Get('/api/ApiLibRole/GetAll', function (data, textStatus, jqXHR) {
                            if (data.success == true) {
                                $('#muserRole').empty();
                                for (var role = 0; role < data.data.length; role++) {
                                    var html = '<option value="' + data.data[role].RoleId + '">' + data.data[role].RoleName + '</option>';
                                    $('#muserRole').append(html);
                                }
                                if ($("#muserRole option[value='" + roleId + "']").length == 1) {
                                    $('#muserRole').val(roleId);
                                }
                                else {
                                    $('#muserRole').val(0);
                                }
                            }
                        });
                    });

                    $('#myModalFooter .btn-primary').attr('value', 'edit');
                    $('#myModalLabel').text('Cập nhật dữ liệu. UserId: ' + self.attr('value'));
                    $('#myModal').modal('show');
                }
                else if (self.find('i').hasClass('fa-trash-o')) {
                    var documentId = self.attr('value');
                    if (confirm('Tiếp tục xóa tài liệu này ?')) {
                        //_dataService.Post('/api/ApiLibDocuments/DeleteData?DocumentId=' + documentId, null, function (data, textStatus, jqXHR) {
                        //    if (data.success == true) {
                        //        self.closest('tr').remove();
                        //    }
                        //});
                    }
                }
            }
        });

        //Save
        $('#myModalFooter .btn-primary').click(function () {
            var self = $(this);
            if (self.attr('value') == 'edit') {
                var data = {
                    UserId: ($('#muserId').val() == '' ? null : $('#muserId').val()),
                    RoleId: ($('#muserRole').val() == '' ? null : $('#muserRole').val())
                };
                _dataService.Post('/api/ApiLibUser/UpdateRoleForUser', data, function (data, textStatus, jqXHR) {
                    if (data.success) {
                        $('#myModal').modal('hide');
                    }
                });
            }
        });
    }

    function ResetModal() {
        $('#muserId').val('');
        $('#muserName').val('');
        $('#muserRole').val('');
    }
}